package com.ego.upload.service.impl;

import com.ego.upload.service.UploadService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadServiceImpl implements UploadService {

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/jpg");

    @Autowired(required = false)
    private FastFileStorageClient storageClient;

    private static final Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Override
    public String upload(MultipartFile file) throws IOException {
        /*
           1. 校验文件大小
           2. 校验文件的媒体类型
           3. 校验文件的内容
         */

        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType();
            if (!suffixes.contains(type)) {
                logger.info("上传文件失败，文件类型不匹配：{}", type);
                return null;
            }
            // 2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                logger.info("上传失败，文件内容不符合要求");
                return null;
            }
            // 2、将图片上传到FastDFS
            // 2.1、获取文件后缀名
           /* String extension = StringUtils.substringAfterLast(file.getOriginalFilename(),
                    ".");*/
            String extension =file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            // 2.2、上传
            StorePath storePath = this.storageClient.uploadFile(
                    file.getInputStream(), file.getSize(), extension, null);
            // 2.3、返回完整路径
            return "http://image.ego.com/" + storePath.getFullPath();
        } catch (Exception e) {
            return null;
        }
       /* // 这几个操作还不怎么会TnT,等同于是照着搬的
        String type = file.getContentType();
        if (!suffixes.contains(type)) {
            return null;
        }
        BufferedImage image = ImageIO.read(file.getInputStream());
        if (image == null) {
            return null;
        }
        String dir = "D:\\Java WorkSpaceStation\\javaTrain\\egoupload\\";
        File dest = new File(dir + file.getOriginalFilename());
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        //上传图片到本地
        file.transferTo(dest);
        return "http://api.ego.com/upload/" + file.getOriginalFilename();*/
    }
}
